// 默认设置
const DEFAULT_SETTINGS = {
  apiKey: '',
  showTodoScroll: true,  // 默认开启待办事项滚动区域
  modelType: 'qwen-turbo'  // 默认使用 qwen-turbo 模型
};

// 保存设置
document.getElementById('save').addEventListener('click', () => {
  console.log('Save button clicked');
  
  const settings = {
    apiKey: document.getElementById('apiKey').value.trim(),
    showTodoScroll: document.getElementById('showTodoScroll').checked,
    modelType: document.getElementById('modelType').value
  };
  
  console.log('Current settings:', settings);
  
  try {
    chrome.storage.sync.set(settings, () => {
      if (chrome.runtime.lastError) {
        console.error('Storage error:', chrome.runtime.lastError);
        showStatus('保存设置时出错: ' + chrome.runtime.lastError.message, false);
        return;
      }
      console.log('Settings saved successfully');
      showStatus('设置已保存', true);
    });
  } catch (error) {
    console.error('Error saving settings:', error);
    showStatus('保存设置时出错', false);
  }
});

// 加载已保存的设置
document.addEventListener('DOMContentLoaded', () => {
  console.log('Loading settings...');
  
  try {
    chrome.storage.sync.get(DEFAULT_SETTINGS, (settings) => {
      if (chrome.runtime.lastError) {
        console.error('Error loading settings:', chrome.runtime.lastError);
        showStatus('加载设置时出错', false);
        return;
      }
      
      console.log('Loaded settings:', settings);
      document.getElementById('apiKey').value = settings.apiKey;
      document.getElementById('showTodoScroll').checked = settings.showTodoScroll;
      document.getElementById('modelType').value = settings.modelType;
    });
  } catch (error) {
    console.error('Error loading settings:', error);
    showStatus('加载设置时出错', false);
  }
});

// 显示状态消息
function showStatus(message, success) {
  const status = document.getElementById('status');
  status.textContent = message;
  status.className = 'status ' + (success ? 'success' : 'error');
  status.style.display = 'block';
  
  // 3秒后隐藏消息
  setTimeout(() => {
    status.style.display = 'none';
  }, 3000);
}

// 导出数据
document.getElementById('exportData').addEventListener('click', async () => {
  try {
    // 获取所有数据
    const data = await Promise.all([
      new Promise((resolve) => chrome.storage.local.get(['notes'], resolve)),
      new Promise((resolve) => chrome.storage.local.get(['todos'], resolve)),
      new Promise((resolve) => chrome.storage.local.get(['stickyNotes'], resolve))
    ]);

    // 合并数据
    const exportData = {
      notes: data[0].notes || [],
      todos: data[1].todos || [],
      stickyNotes: data[2].stickyNotes || [],
      exportDate: new Date().toISOString()
    };

    // 创建并下载文件
    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `mark-anything-backup-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    showStatus('数据导出成功', true);
  } catch (error) {
    console.error('导出数据失败:', error);
    showStatus('导出数据失败: ' + error.message, false);
  }
});

// 导入按钮点击事件
document.getElementById('importData').addEventListener('click', () => {
  document.getElementById('importFile').click();
});

// 处理文件导入
document.getElementById('importFile').addEventListener('change', async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  try {
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const data = JSON.parse(e.target.result);
        
        // 验证数据格式
        if (!data.notes || !data.todos || !data.stickyNotes) {
          throw new Error('无效的备份文件格式');
        }

        // 保存导入的数据
        await Promise.all([
          new Promise((resolve, reject) => {
            chrome.storage.local.set({ notes: data.notes }, () => {
              if (chrome.runtime.lastError) reject(chrome.runtime.lastError);
              else resolve();
            });
          }),
          new Promise((resolve, reject) => {
            chrome.storage.local.set({ todos: data.todos }, () => {
              if (chrome.runtime.lastError) reject(chrome.runtime.lastError);
              else resolve();
            });
          }),
          new Promise((resolve, reject) => {
            chrome.storage.local.set({ stickyNotes: data.stickyNotes }, () => {
              if (chrome.runtime.lastError) reject(chrome.runtime.lastError);
              else resolve();
            });
          })
        ]);

        showStatus('数据导入成功', true);
      } catch (error) {
        console.error('导入数据失败:', error);
        showStatus('导入数据失败: ' + error.message, false);
      }
    };
    reader.readAsText(file);
  } catch (error) {
    console.error('读取文件失败:', error);
    showStatus('读取文件失败: ' + error.message, false);
  }
  
  // 清除文件选择，这样同一个文件可以再次选择
  event.target.value = '';
}); 